<template>
  <div class="users-container">
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showUserDialog('add')">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
      </div>
    </div>
    
    <div class="filter-container">
      <el-input
        v-model="searchQuery"
        placeholder="搜索用户名/姓名/手机号"
        clearable
        class="search-input"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      
      <el-select v-model="roleFilter" placeholder="角色筛选" clearable @change="handleSearch">
        <el-option label="全部角色" value="" />
        <el-option
          v-for="role in roleOptions"
          :key="role.value"
          :label="role.label"
          :value="role.value"
        />
      </el-select>
      
      <el-select v-model="statusFilter" placeholder="状态筛选" clearable @change="handleSearch">
        <el-option label="全部状态" value="" />
        <el-option label="启用" value="1" />
        <el-option label="禁用" value="0" />
      </el-select>
    </div>
    
    <el-table
      :data="filteredUsers"
      border
      stripe
      style="width: 100%"
    >
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="mobile" label="手机号" width="120" />
      <el-table-column prop="email" label="邮箱" min-width="180" />
      <el-table-column prop="roleName" label="角色" width="120">
        <template #default="{ row }">
          <el-tag :type="getRoleTagType(row.role)">{{ row.roleName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="changeUserStatus(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="showUserDialog('edit', row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :total="totalUsers"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="550px"
    >
      <el-form :model="userForm" label-width="100px" ref="userFormRef" :rules="userRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="userForm.mobile" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="dialogType === 'add'" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除用户"
      width="400px"
    >
      <div class="delete-confirm">
        <el-icon class="warning-icon"><WarningFilled /></el-icon>
        <p>确定要删除用户 <strong>{{ userToDelete?.name }}</strong> 吗？</p>
        <p class="warning-text">删除后将无法恢复，请谨慎操作！</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { 
  Plus, 
  Search, 
  WarningFilled 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索和筛选
const searchQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')

// 分页
const totalUsers = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('add') // add 或 edit
const userFormRef = ref(null)
const deleteDialogVisible = ref(false)
const userToDelete = ref(null)

// 角色选项
const roleOptions = [
  { value: 'admin', label: '管理员' },
  { value: 'manager', label: '项目经理' },
  { value: 'worker', label: '施工负责人' }
]

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 用户表单
const userForm = ref({
  id: '',
  username: '',
  name: '',
  mobile: '',
  email: '',
  password: '',
  role: '',
  roleName: '',
  status: 1,
  createTime: ''
})

// 模拟用户数据
const users = ref([
  {
    id: 1,
    username: 'admin',
    name: '系统管理员',
    mobile: '13800138000',
    email: 'admin@example.com',
    role: 'admin',
    roleName: '管理员',
    status: 1,
    createTime: '2023-01-01 10:00:00'
  },
  {
    id: 2,
    username: 'zhangsan',
    name: '张三',
    mobile: '13800138001',
    email: 'zhangsan@example.com',
    role: 'manager',
    roleName: '项目经理',
    status: 1,
    createTime: '2023-01-02 10:00:00'
  },
  {
    id: 3,
    username: 'lisi',
    name: '李四',
    mobile: '13800138002',
    email: 'lisi@example.com',
    role: 'manager',
    roleName: '项目经理',
    status: 1,
    createTime: '2023-01-03 10:00:00'
  },
  {
    id: 4,
    username: 'wangwu',
    name: '王五',
    mobile: '13800138003',
    email: 'wangwu@example.com',
    role: 'worker',
    roleName: '施工负责人',
    status: 1,
    createTime: '2023-01-04 10:00:00'
  },
  {
    id: 5,
    username: 'zhaoliu',
    name: '赵六',
    mobile: '13800138004',
    email: 'zhaoliu@example.com',
    role: 'worker',
    roleName: '施工负责人',
    status: 0,
    createTime: '2023-01-05 10:00:00'
  }
])

// 根据筛选条件过滤用户
const filteredUsers = computed(() => {
  let result = users.value.filter(user => {
    const matchQuery = searchQuery.value
      ? user.username.includes(searchQuery.value) ||
        user.name.includes(searchQuery.value) ||
        user.mobile.includes(searchQuery.value)
      : true
    
    const matchRole = roleFilter.value
      ? user.role === roleFilter.value
      : true
    
    const matchStatus = statusFilter.value !== ''
      ? user.status === parseInt(statusFilter.value)
      : true
    
    return matchQuery && matchRole && matchStatus
  })
  
  totalUsers.value = result.length
  
  // 模拟分页
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  
  return result.slice(startIndex, endIndex)
})

// 获取角色标签类型
const getRoleTagType = (role) => {
  const types = {
    'admin': 'danger',
    'manager': 'warning',
    'worker': 'info'
  }
  return types[role] || 'info'
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 显示用户表单对话框
const showUserDialog = (type, user = null) => {
  dialogType.value = type
  
  // 重置表单
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  
  if (type === 'add') {
    userForm.value = {
      id: '',
      username: '',
      name: '',
      mobile: '',
      email: '',
      password: '',
      role: '',
      roleName: '',
      status: 1,
      createTime: ''
    }
  } else if (type === 'edit' && user) {
    // 编辑时不显示密码字段
    userForm.value = { ...user }
    delete userForm.value.password
  }
  
  dialogVisible.value = true
}

// 提交用户表单
const submitUserForm = () => {
  userFormRef.value.validate((valid) => {
    if (!valid) return
    
    // 获取角色名称
    const roleObj = roleOptions.find(item => item.value === userForm.value.role)
    userForm.value.roleName = roleObj ? roleObj.label : ''
    
    if (dialogType.value === 'add') {
      // 添加用户
      const newUser = {
        ...userForm.value,
        id: Date.now(), // 模拟ID
        createTime: formatDateTime(new Date())
      }
      users.value.push(newUser)
      ElMessage.success('用户添加成功')
    } else {
      // 更新用户
      const index = users.value.findIndex(u => u.id === userForm.value.id)
      if (index !== -1) {
        users.value[index] = { ...users.value[index], ...userForm.value }
        ElMessage.success('用户更新成功')
      }
    }
    
    dialogVisible.value = false
  })
}

// 修改用户状态
const changeUserStatus = (user) => {
  const statusText = user.status === 1 ? '启用' : '禁用'
  ElMessage.success(`已${statusText}用户: ${user.name}`)
}

// 删除用户
const handleDelete = (user) => {
  userToDelete.value = user
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = () => {
  if (!userToDelete.value) return
  
  const index = users.value.findIndex(u => u.id === userToDelete.value.id)
  if (index !== -1) {
    users.value.splice(index, 1)
    ElMessage.success('用户删除成功')
    deleteDialogVisible.value = false
  }
}

// 格式化日期时间
const formatDateTime = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 初始化
onMounted(() => {
  // 获取用户列表
  // 在实际项目中，这里通常会发起API请求获取数据
  totalUsers.value = users.value.length
})
</script>

<style lang="scss" scoped>
.users-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .page-title {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .filter-container {
    background-color: #f5f7fa;
    padding: 16px;
    border-radius: 8px;
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
    
    .search-input {
      width: 300px;
    }
    
    .el-select {
      width: 180px;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .delete-confirm {
    text-align: center;
    padding: 20px 0;
    
    .warning-icon {
      font-size: 48px;
      color: #E6A23C;
      margin-bottom: 16px;
    }
    
    p {
      margin: 8px 0;
      font-size: 16px;
    }
    
    .warning-text {
      color: #F56C6C;
      font-weight: bold;
    }
  }
}
</style> 